package com.test.testmap

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.PointCollection
import com.esri.arcgisruntime.geometry.Polygon
import com.esri.arcgisruntime.geometry.Polyline
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.view.BackgroundGrid
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.TextSymbol
import com.test.testmap.MapUtil.loadTianDiTu
import com.test.testmap.databinding.MapActivityBinding


class MapActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback {
    private var _binding: MapActivityBinding? = null
    private var arcGisMap: ArcGISMap? = null

    /**
     * 添加个人元素的图层
     */
    private var mGraphicsOverlay: GraphicsOverlay? = null

    private var pmsSelf: PictureMarkerSymbol? = null
    private var pmsMarker: PictureMarkerSymbol? = null

    private var pointListGraphic: MutableList<Graphic>? = ArrayList()
    private var lineListGraphic: MutableList<Graphic>? = ArrayList()

    private var selfIcon: Graphic? = null
    private var markerIcon: Graphic? = null
    private var pointGraphic: Graphic? = null
    private var textGraphic: Graphic? = null
    private var graphicArea: Graphic? = null

    private var selfDrawable: BitmapDrawable? = null
    private var markerDrawable: BitmapDrawable? = null

    /**
     * 点集合
     */
    private val mPointCollection = PointCollection(SpatialReferences.getWgs84())

    private var allPermissions = arrayOf(
        Manifest.permission.INTERNET,
        Manifest.permission.ACCESS_FINE_LOCATION
    )

    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    private var mPermissionList: MutableList<String> = ArrayList()

    private val lat = 34.17229570410301
    private val lon = 108.84629776270128

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = MapActivityBinding.inflate(layoutInflater)
        setContentView(_binding!!.root)
        //1 请求网络权限 定位权限
        requestPermission()
        //2 初始化控件
        initView()
        //3 通过定位拿到当前位置经纬度，移动地图中心点到当前位置。添加marker在当前位置
        //TODO 初始化定位相关内容
    }


    private fun initView() {
        _binding?.btnCenter?.setOnClickListener {
            toCenterPoint()
        }

        _binding?.btnDrawPoint?.setOnClickListener {
            drawPoint()
        }
        _binding?.btnDrawLine?.setOnClickListener {
            drawLine()
        }
        _binding?.btnDrawArea?.setOnClickListener {
            drawArea()
        }
        _binding?.btnDrawText?.setOnClickListener {
            drawText()
        }
        _binding?.btnDrawMarker?.setOnClickListener {
            drawMarker()
        }

    }


    /**
     * 初始化地图控件
     * */
    private fun initMap() {
        //去除ESRI图标及点击跳转
        _binding?.mapView?.isAttributionTextVisible = false
        //比例尺 TODO 暂未添加
        arcGisMap = ArcGISMap(loadTianDiTu())
        _binding?.mapView?.map = arcGisMap
        addGraphicsOverlay()
        toCenterPoint()
        removeBackgroundGrid()
    }

    private fun removeBackgroundGrid() {
        //去掉背景的隔线
        val mainBackgroundGrid = BackgroundGrid()
        mainBackgroundGrid.color = -0x1
        mainBackgroundGrid.gridLineColor = -0x1
        mainBackgroundGrid.gridLineWidth = 0f
        _binding?.mapView?.backgroundGrid = mainBackgroundGrid
    }

    /**
     * 添加个人元素图层
     * */
    private fun addGraphicsOverlay() {
        mGraphicsOverlay = GraphicsOverlay()
        _binding?.mapView?.graphicsOverlays?.add(mGraphicsOverlay)
    }

    private fun toCenterPoint() {
        //默认居中点 你也可以替换为定位获取到的经纬度，并且去实现位置变更自动移动地图上的marker点位置
        val center = Point(lon, lat, SpatialReferences.getWgs84())
        _binding?.mapView?.setViewpointCenterAsync(center, 70000.0)
        //添加marker
        if (pmsSelf == null) {
            pmsSelf = PictureMarkerSymbol(getSelfDrawable())
            pmsSelf!!.loadAsync()
            pmsSelf!!.addDoneLoadingListener {
                //设置marker大小
                pmsSelf!!.width = 20f
                pmsSelf!!.height = 20f
            }
        }
        if (selfIcon == null) {
            //初始化selfIcon
            selfIcon = Graphic(center, pmsSelf)
            mGraphicsOverlay!!.graphics.add(selfIcon)
        } else {
            //selfIcon 已存在，直接更新位置
            selfIcon!!.geometry = center
        }
    }


    private fun drawMarker() {
        //如果存在则取消
        if (markerIcon != null) {
            mGraphicsOverlay!!.graphics.remove(markerIcon)
            markerIcon = null
            pmsMarker = null
            return
        }
        val center = Point(lon + 0.002, lat - 0.002, SpatialReferences.getWgs84())
        //添加marker
        if (pmsMarker == null) {
            pmsMarker = PictureMarkerSymbol(getMarkerDrawable())
            pmsMarker!!.loadAsync()
            pmsMarker!!.addDoneLoadingListener {
                //设置marker大小
                pmsMarker!!.width = 20f
                pmsMarker!!.height = 20f
            }
        }
        if (markerIcon == null) {
            //初始化selfIcon
            markerIcon = Graphic(center, pmsMarker)
            mGraphicsOverlay!!.graphics.add(markerIcon)
        } else {
            //selfIcon 已存在，直接更新位置
            markerIcon!!.geometry = center
        }
    }


    private fun drawText() {
        if (textGraphic != null) {
            mGraphicsOverlay!!.graphics.remove(textGraphic)
            textGraphic = null
            return
        }

        val center = Point(lon - 0.0003, lat + 0.0003, SpatialReferences.getWgs84())
        val textSymbol = TextSymbol(
            20f,
            "绘制文字",
            Color.RED,
            TextSymbol.HorizontalAlignment.CENTER,
            TextSymbol.VerticalAlignment.MIDDLE
        )
        textGraphic = Graphic(center, textSymbol)
        mGraphicsOverlay!!.graphics.add(textGraphic)
    }


    private fun drawArea() {
        if (graphicArea != null) {
            mPointCollection.clear()
            mGraphicsOverlay!!.graphics.remove(graphicArea)
            graphicArea = null
            return
        }
        mPointCollection.add(Point(lon - 0.01, lat - 0.01))
        mPointCollection.add(Point(lon - 0.01, lat + 0.01))
        mPointCollection.add(Point(lon + 0.01, lat + 0.01))
        mPointCollection.add(Point(lon + 0.01, lat - 0.01))
        mPointCollection.add(Point(lon - 0.01, lat - 0.01))

        val polygon = Polygon(mPointCollection)
        val lineSymbol = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.GREEN, 3.0f)
        val simpleFillSymbol = SimpleFillSymbol(
            SimpleFillSymbol.Style.SOLID,
            Color.parseColor("#33e97676"),
            lineSymbol
        )
        graphicArea = Graphic(polygon, simpleFillSymbol)
        mGraphicsOverlay!!.graphics.add(graphicArea)
    }


    private fun drawLine() {
        if (mPointCollection.size > 0) {
            mPointCollection.clear()
            lineListGraphic?.let { mGraphicsOverlay!!.graphics.removeAll(it) }
            lineListGraphic?.clear()
            pointListGraphic?.let { mGraphicsOverlay!!.graphics.removeAll(it) }
            pointListGraphic?.clear()
            return
        }

        mPointCollection.add(Point(lon - 0.0003, lat + 0.0003))
        mPointCollection.add(Point(lon - 0.1003, lat + 0.1003))
        val polyline = Polyline(mPointCollection)
        // 绘制点
        for (point in mPointCollection) {
            val simpleMarkerSymbol =
                SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10f)
            val pointGraphic = Graphic(point, simpleMarkerSymbol)
            pointListGraphic?.add(pointGraphic)
        }
        pointListGraphic?.let { mGraphicsOverlay!!.graphics.addAll(it) }

        //线 这里是为了画黑白带间隔的线。如果是纯色线，只需要一个simpleLineSymbol就行
        val simpleLineSymbol =
            SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#ffffff"), 3f)
        val simpleLineSymbol1 =
            SimpleLineSymbol(SimpleLineSymbol.Style.SHORT_DASH, Color.parseColor("#000000"), 3f)
        val graphic = Graphic(polyline, simpleLineSymbol)
        val graphic1 = Graphic(polyline, simpleLineSymbol1)
        lineListGraphic?.add(graphic)
        lineListGraphic?.add(graphic1)
        lineListGraphic?.let { mGraphicsOverlay!!.graphics.addAll(it) }
    }


    private fun drawPoint() {
        //第一次添加点到地图上，第二次点击清除上一次添加的点
        if (pointGraphic == null) {
            val center = Point(lon + 0.018, lat + 0.018, SpatialReferences.getWgs84())
            val simpleMarkerSymbol =
                SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10f)
            pointGraphic = Graphic(center, simpleMarkerSymbol)
            mGraphicsOverlay!!.graphics.add(pointGraphic)
        } else {
            mGraphicsOverlay!!.graphics.remove(pointGraphic)
            pointGraphic = null
        }
    }

    /**
     * 获取bitmapDrawable类型的icon
     * */
    private fun getSelfDrawable(): BitmapDrawable? {
        if (selfDrawable == null) {
            val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.work)
            selfDrawable = BitmapDrawable(resources, bitmap)
        }
        return selfDrawable
    }

    private fun getMarkerDrawable(): BitmapDrawable? {
        if (markerDrawable == null) {
            val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.typee)
            markerDrawable = BitmapDrawable(resources, bitmap)
        }
        return markerDrawable
    }


    private fun requestPermission() {
        //build.gradle中targetSdkVersion>=23时，必须动态申请权限
        mPermissionList.clear()
        for (i in allPermissions.indices) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    allPermissions[i]
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                mPermissionList.add(allPermissions[i])
            }
        }
        if (mPermissionList.isEmpty()) { //未授予的权限为空，表示都授予了
            Log.i(MapConstants.TAG, "all permissions is granted")
            //只有在权限被全部授予了，才可以开启所有服务
            initMap()
        } else { //请求权限方法
            Log.i(MapConstants.TAG, "request permission")
            val permissions = mPermissionList.toTypedArray() //将List转为数组
            ActivityCompat.requestPermissions(
                this,
                permissions,
                MapConstants.REQUEST_READ_PHONE_STATE
            )
        }
    }

    /**
     * 权限申请回调
     * */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var mGrantedNum = 0
        if (requestCode == MapConstants.REQUEST_READ_PHONE_STATE) {
            for (i in grantResults.indices) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    mGrantedNum++
                } else {
                    finish()
                }
            }
            if (mGrantedNum == mPermissionList.size) {
                Log.i(MapConstants.TAG, "=====initMap")
                initMap()
            } else {
                finish()
            }
        } else {
            finish()
        }
    }


    override fun onPause() {
        _binding?.mapView?.pause()
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        _binding?.mapView?.resume()
    }
}